const app = getApp()
// eslint-disable-next-line no-undef
const plugin = requirePlugin('zsPlugin')
import {
    getApplyDetail,
    getJobList,
    getJobPayCompany
} from '../../api/job'
import {
    getadvancedetailapi
} from '../../api/advance'
import {
    querySalaryCard
} from '../../utils/salary-card'
import {
    getPaidadvance,
    getPaid,
    getSalaryAli
} from '../../api/get-paid'
import user from '../../utils/user'
import {
    paid
} from '../../utils/dictionaryKey'
import {
    wait
} from '../../utils/util'
import {
    clockInPageData
} from '../../api/app'
Page({
    data: {
        jobList: [],
        workDetail: {},
        teamWorkers: [],
        workDate: '',
        isOpenSalaryCard: true,
        payObj: {},
        payid: null,
        timer: null,
        getPayStatus: 0,
        order: '',
        frompay: '',
        platform: 'wechat',
        openId: user.openid,
    },
    static: {
        subMchid: '',
        jobPageNum: 1,
        jobPageSize: 10,
        hasJobNext: true,
        isfalse: ''
    },
    onLoad(options) {
        user.waitLogin().then(async () => {
            console.log(options, 'options')
            this.setData({
                isOpenSalaryCard: user.isOpenSalaryCard,
                payid: options.payid,
                order: options.order,
                isfalse: options.isfalse,
                frompay: options.frompay,
                ['payObj.type']: options.type,
                ['payObj.title']: options.title,
                ['payObj.content']: options.content,
                platform: options.platform || 'wechat',
                openId: user.openid,
            })
            if (options.frompay === 'true') {
                if (!options.isfalse) {
                    this.data.timer = setTimeout(async () => {
                        if (this.data.platform === 'wechat') {
                            await this.getWechatSalaryStatus()
                        } else {
                            await this.getAlipaySalaryStatus()
                        }
                        clearTimeout(this.data.timer)
                    }, 10000)
                }
            } else if (options.frompay === 'false') {
                if (!options.isfalse) {
                    const res = await getadvancedetailapi({
                        id: options.payid
                    })
                    this.data.timer = setTimeout(async () => {
                        const result = await getPaidadvance({
                            detailOrderNo: res.detailOrderNo,
                            id: res.recordId,
                            phone: res.phone,
                            transferScene: ''
                        })
                        if (result && result.type === '转账失败') {
                            this.setData({
                                ['payObj.type']: 'warn',
                                ['payObj.title']: result.msg,
                                ['payObj.content']: result.msg ? result.msg : '您的账号异常，请联系领队！',
                            })
                        } else if (result && result.msg) {
                            this.setData({
                                ['payObj.type']: 'success',
                                ['payObj.title']: result.msg,
                                ['payObj.content']: '提现成功',
                            })
                        }
                        clearTimeout(this.data.timer)
                    }, 10000)
                }
            }
            if (options.jobid) {
                this.setData({
                    payid: options.payid,
                    jobId: options.jobid,
                    ['payObj.type']: options.type,
                    ['payObj.title']: options.title,
                    ['payObj.phone']: options.phone,
                    ['payObj.content']: options.content,
                })

                getApplyDetail({
                    jobId: options.jobid
                }).then(res => {
                    res.params.jobLocation = res.params.jobLocation.split(',')
                    res.longitude = res.params.jobLocation[0]
                    res.latitude = res.params.jobLocation[1]
                    this.setData({
                        workDetail: res
                    })
                })
            }
            console.log(this.data.jobId, '有没有jobId')
            if (options.id) {
                options.content = paid[options.content] || options.content
                this.setData({
                    payObj: options
                })
                console.log(this.data.payObj, 'this.data.payObj')
                this.getJobPayCompany()
                this.getJob(true, true)
            }
        })
        const eventChannel = this.getOpenerEventChannel()
        try {
            eventChannel.on('reportDate', (data) => {
                this.setData({
                    workDate: data.data.length > 2 ? (data.data[0] + '...共' + data.data.length + '天') : data.data.join(',')
                })
            })
        } catch (e) {
            console.log(e)
        }
    },
    onHide() {
        clearTimeout(this.data.timer)
    },
    onShow() {
        if (this.static.subMchid) {
            this.static.subMchid = ''
            querySalaryCard(this.data.workDetail.companyId).then(() => {
                app.toast('授权成功！', 'success')
                this.setData({
                    isOpenSalaryCard: true
                })
            })
        }
    },
    onGoHome() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    async getJobPayCompany() {
        const result = await getJobPayCompany({
            companyId: this.data.payObj.id
        })
        this.setData({
            workDetail: result
        })
        console.log(result, 'resultresult')
    },
    onAddressNav() {
        wx.openLocation({
            latitude: Number(this.data.workDetail.latitude), // 维度
            longitude: Number(this.data.workDetail.longitude), // 经度
            name: this.data.workDetail.params.jobAddress, // 目的地定位名称
            scale: 15, // 缩放比例
            address: this.data.workDetail.params.jobAddress // 导航详细地址
        })
    },
    onGoDetail() {
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + this.data.workDetail.jobId
        })
    },
    makephone() {
        console.log(this.data, '电话')
        if (this.data.payObj.phone) {
            wx.makePhoneCall({
                phoneNumber: this.data.payObj.phone
            })
            return
        }
        wx.showActionSheet({
            itemList: this.data.workDetail.params.phoneList.length > 6 ? this.data.workDetail.params.phoneList.splice(0, 6) : this.data.workDetail.params.phoneList,
            success: (result) => {
                wx.makePhoneCall({
                    phoneNumber: this.data.workDetail.params.phoneList[result.tapIndex]
                })
            },
            fail: () => {},
            complete: () => {}
        })
    },
    // 获取招聘中岗位列表
    async getJob(empty = false, reRendering) {
        if (!this.static.hasJobNext) {
            return
        }
        if (empty) {
            this.setData({
                workList: [],
                total: 0,
                pageNum: 1
            })
        }
        const result = await getJobList({
            pageNum: this.static.jobPageNum,
            pageSize: this.static.jobPageSize
        })
        this.static.hasJobNext = result.hasNextPage
        this.static.jobPageNum += 1
        this.data.jobList.push(...result.list.map(item => {
            item.jobTag = item.jobTag ? item.jobTag.split(';') : []
            return item
        }))
        console.log(this.data.jobList)
        this.setData({
            jobList: this.data.jobList
        })
        wx.lin.renderWaterFlow(this.data.jobList, reRendering, (res) => {
            console.log(res, 'resres')
        })
    },
    // 先不 使用 因为只需要前十个
    onArriveBottom() {
        return
    },
    // 去详情页
    goWorkDetail(event) {
        console.log(event.detail.item, 'event')
        this.setData({
            jobInfo: event.detail.item
        })
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + this.data.jobInfo.id
        })
    },
    // wx.previewImage(Object object)
    onPreviewImage() {
        console.log('点击了', [{
            url: this.data.workDetail.params.qyWxQrcodeUrl,
            type: 'image'
        }])

        // wx.previewImage({
        //     urls: [this.data.workDetail.params.qyWxQrcodeUrl],
        //     showmenu: true
        // })
        wx.previewImage({
            current: this.data.workDetail.params.qyWxQrcodeUrl,
            urls: [this.data.workDetail.params.qyWxQrcodeUrl],
            showmenu: true
        })
    },
    async getWechatSalaryStatus() {
        const result = await getPaid({
            id: this.data.payid,
            detailOrderNo: this.data.order,
            transferScene: ''
        })
        if (result && result.type === '转账失败') {
            this.setData({
                ['payObj.type']: 'warn',
                ['payObj.title']: result.msg,
                ['payObj.content']: result.msg ? result.msg : '您的账号异常，请联系领队！',
            })
        } else if (result && result.msg) {
            this.setData({
                ['payObj.type']: 'success',
                ['payObj.title']: result.msg,
                ['payObj.content']: '提现成功',
            })
        }
    },

    async getAlipaySalaryStatus() {
        const res = await getSalaryAli({
            id: this.data.payid,
            phone: user.phone,
            detailOrderNo: this.data.order
        }).catch(err => {
            this.setData({
                ['payObj.type']: 'warn',
                ['payObj.title']: err?.msg || '提现失败',
                ['payObj.content']: err?.msg || '提现失败',
            })
            throw new Error('支付宝领薪失败')
        })
        if (res?.msg === '转账处理中，请稍后') {
            await wait(3000)
            this.setData({
                ['payObj.type']: 'warn'
            })
            this.getAlipaySalaryStatus()
        } else {
            this.setData({
                ['payObj.type']: 'success',
                ['payObj.content']: res?.msg || '提现成功',
            })
        }
    },
    bannerCallBack(e) {
        let item = e.detail.item
        if (item.jumpType == 2) {
            let url = encodeURIComponent(item.h5Url)
            wx.navigateTo({ // 需创建一个webview页面，供h5页面跳转，页面名称可自定义，但需与此处跳转匹配。
                url: '/pages/zsWebView/zsWebView?url=' + url,
            })
        } else if (item.jumpType == 3) {
            wx.openEmbeddedMiniProgram({
                appId: item.appId,
                path: item.appPath
            })
        } else if (item.jumpType == 6) {
            let obj = plugin.getUrlInfo(item)
            wx.navigateToMiniProgram({
                appId: obj.appId,
                path: obj.pages,
                extraData: obj.miniProData
            })
        }
    },
})